package com.plate.auth.service;

import com.plate.api.system.domain.SysUser;
import com.plate.api.system.remoteService.RemoteSystemService;
import com.plate.auth.domain.LoginUser;
import com.plate.common.core.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description TODO
 * @Author jiaxd
 * @Date 2023年10月22日 12:34
 * @Version 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteSystemService remoteSystemService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库读取用户数据
        Result<SysUser> result = remoteSystemService.getUserByUsername(username, "");
        SysUser sysUser = result.getData();
        // 用户不存在, 抛出异常
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 将数据库形式的roles解析为UserDetails的权限集
        // 将权限集字符串切割为权限对象列表
        return new LoginUser(sysUser);
    }
}
